package com.takeoff.iot.modbus.netty.handle;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.takeoff.iot.modbus.common.message.ModbusMessage;
import com.takeoff.iot.modbus.netty.channel.ModbusChannel;
import com.takeoff.iot.modbus.netty.channel.ModbusContextChannel;
import com.takeoff.iot.modbus.netty.device.ModbusControlCentre;
import com.takeoff.iot.modbus.netty.listener.ModbusListener;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.util.encoders.Hex;

/**
 * 类功能说明：自定义数据接收监听器<br/>
 * 公司名称：TF（腾飞）开源 <br/>
 * 作者：luorongxi <br/>
 */
@Slf4j
@Sharable
public class ModbusListenerHandler extends SimpleChannelInboundHandler<ModbusMessage> {

	private Map<Integer, List<ModbusListener>> listeners = new ConcurrentHashMap<>();
	private ModbusControlCentre centre;

	public ModbusListenerHandler(){
	}

	public ModbusListenerHandler(ModbusControlCentre centre){
		this.centre = centre;
	}

	public void addListener(int command, ModbusListener listener){
		List<ModbusListener> pre = null;
		if(hasListener(command)){
			pre = listeners.get(command);
		}else{
			pre = new ArrayList<>();
		}
		pre.add(listener);
		listeners.put(command, pre);
//		return pre;
	}

	public void removeListener(int command){
		listeners.remove(command);
	}

	public boolean hasListener(int command){
		return listeners.get(command) != null;
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, ModbusMessage msg) throws Exception {
		log.debug("收到上传消息: {}", Hex.toHexString(msg.toBytes()));
		log.debug("解析出的操作码为: {}", msg.command());
		List<ModbusListener> listener = listeners.get(msg.command());
		ModbusChannel channel = centre == null ? new ModbusContextChannel(ctx) : centre.get(msg.deviceGroup());
		if(listener != null){
			for(ModbusListener modbusListener : listener){
				modbusListener.receive(channel == null ? new ModbusContextChannel(ctx) : channel, msg);
			}

		}

//		else{
		//不管收到啥都先丢到mq处理
		List<ModbusListener> otherslistener = listeners.get(ModbusMessage.OTHERS);
		for(ModbusListener modbusListener : otherslistener){
			ModbusChannel channel2 = centre == null ? new ModbusContextChannel(ctx) : centre.get(msg.deviceGroup());
			modbusListener.receive(channel2 == null ? new ModbusContextChannel(ctx) : channel2, msg);
		}

//		}
	}

}
